package com.styytech.dadabao.ui.login;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.RequestParams;
import com.styytech.dadabao.DadaApplication;
import com.styytech.dadabao.R;
import com.styytech.dadabao.api.requestresult.LoginResult;
import com.styytech.dadabao.api.response.AbstractResponseResult;
import com.styytech.dadabao.api.templates.HttpRequest;
import com.styytech.dadabao.base.BaseActivity;
import com.styytech.dadabao.constant.ConstantsCommon;
import com.styytech.dadabao.constant.ConstantsServerUrl;
import com.styytech.dadabao.exception.ArgumentsException;
import com.styytech.dadabao.exception.RequestException;
import com.styytech.dadabao.ui.main.GesturePasswordActivity;
import com.styytech.dadabao.utils.CommonUtils;
import com.styytech.dadabao.utils.Md5Utils;
import com.styytech.dadabao.utils.NumberUtil;
import com.styytech.dadabao.utils.SpUser;
import com.styytech.dadabao.widge.dialog.CustomLoadingDialog;

/**
 * 登录界面
 */
@ContentView(R.layout.activity_login)
public class LoginActivity extends BaseActivity implements View.OnClickListener {


    /*手机号*/
    @ViewInject(R.id.et_number)
    EditText et_number;
    /*密码*/
    @ViewInject(R.id.et_password)
    EditText et_password;
    /*登录按钮*/
    @ViewInject(R.id.bt_login)
    Button bt_login;
    /*注册按钮*/
    @ViewInject(R.id.tv_register)
    TextView tv_register;
    /*忘记密码按钮*/
    @ViewInject(R.id.tv_reset_passwrod)
    TextView tv_reset_passwrod;

    /*上下文*/
    private Context context;
    /*loading框*/
    private CustomLoadingDialog mdlg;

    private boolean isComplete = false;// false：还未符合完成的条件，true：已经符合

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        initView();
        initData();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        DadaApplication.addActivity(this);
        setTopBar("用户登录", View.VISIBLE);

        /*设置topBar视图*/
        ly_right.setVisibility(View.VISIBLE);
        tv_ok.setVisibility(View.VISIBLE);
        tv_ok.setText("注册");
        tv_cancel.setText("取消");
        int paddingleft = CommonUtils.dip2px(context, 15);
        tv_cancel.setPadding(paddingleft, 0, 0, 0);

        /*绑定监听*/
        tv_ok.setOnClickListener(this);
        tv_reset_passwrod.setOnClickListener(this);//忘记密码
        et_number.addTextChangedListener(phoneNumberEdit);
        et_password.addTextChangedListener(passwordEdit);
    }

    private void initData() {
        /*获取上次成功登录的账号*/
        String number = SpUser.getUserName(context);
        et_number.setText(number);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_login:// 登录
                SpUser.setUserToken(context, null);// 登录前，先清除token
                login();
                break;
            case R.id.tv_ok://注册
                startMainActivity(RegisterActivity.class);
                break;
            case R.id.tv_reset_passwrod://忘记密码
                startMainActivity(ResetActivity.class);
                break;
        }
    }


    /**
     * 启动界面
     *
     * @param cls 需要启动的界面类
     */
    private void startMainActivity(Class<?> cls) {
        Intent intent = new Intent(context, cls);
        startActivity(intent);
    }

    /**
     * 提示消息
     *
     * @param str 需要提示的消息
     */
    private void toast(String str) {
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
    }

    /**
     * 登录事件处理
     */
    private void login() {
        /*获取用户输入的账号，密码*/
        String userCd = et_number.getText().toString().trim();
        String password = et_password.getText().toString().trim();
        /*条件过滤*/
        if (userCd.isEmpty()) {
            //账号不能为空
            toast(getResources().getString(R.string.account_no_empty));
            return;
            //        } else if (phoneNum.length() != 11) {
        } else if (NumberUtil.checkNumber(userCd).getType() == NumberUtil.PhoneType.INVALIDPHONE) {
            toast(getResources().getString(R.string.number_to_right));
            return;
        } else if (password.isEmpty()) {
            //密码不能为空
            toast(getResources().getString(R.string.pwd_no_empty));
            return;
        } else if (password.length() < 6 || password.length() > 30) {
            //密码不能少于6位
            toast(getResources().getString(R.string.pwd_too_low));
            return;
        }

        // 显示Loading对话框
        mdlg = CommonUtils.getCustomLoadingDialog(context, mdlg, "登录", true);
        mdlg.show();

        /*登录请求参数*/
        RequestParams params = new RequestParams();
        String mD5Pass = Md5Utils.hash(password);// 密码加密
        params.put("userCd", userCd);
        params.put("password", mD5Pass);
        params.put("versionNo","1.1");
        params.put("driverType","android");
        /*登录请求*/
        loginRequest(params);

    }

    /**
     * 登录请求
     *
     * @param params 请求参数
     */
    private void loginRequest(RequestParams params) {
        String url = ConstantsServerUrl.getLoginUrl();// 登录请求URL接口
        //获取验证码
        LoginResult loginResult = new LoginResult(context, responseResult);
        try {
            new HttpRequest(this).doPost(loginResult, url, params);
        } catch (ArgumentsException e) {
            e.printStackTrace();
        } catch (RequestException e) {
            e.printStackTrace();
        }
    }

    /**
     * 登录请求结果处理
     */
    AbstractResponseResult responseResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            CommonUtils.closeDialog(mdlg);
            // 保存成功登录的账号
            SpUser.setUserName(context, et_number.getText().toString().trim());
            // 保存用户密码
            SpUser.setUserInfo(context, ConstantsCommon.USER_PASSWORD, et_password.getText().toString());
            // 如果开启了，进入修改手势密码
            if (SpUser.getGestureSwitch(context)) {
                startMainActivity(GesturePasswordActivity.class);
            }
            hideSoftInput();
            finish();
        }

        @Override
        public void executeError(String message, int errorCode) {
            CommonUtils.showToastMsg(context, "" + message);
            CommonUtils.closeDialog(mdlg);
        }

        @Override
        public void HttpError(String message, int errorCode) {
            CommonUtils.closeDialog(mdlg);
            CommonUtils.showToastMsg(context, "" + message);
        }
    };

    /**
     * 手机号输入监听
     */
    private TextWatcher phoneNumberEdit = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
//            Log.i("123", "phoneNumberEdit-start:" + start + before);
            if (et_password.length() >= 6) {
                isComplete = true;
            } else {
                isComplete = false;
            }
            if ((et_number.length() > 0) && isComplete) {
                bt_login.setBackgroundResource(R.drawable.btn_common_selector);
//                bt_login.setClickable(true);
            } else {
                bt_login.setBackgroundResource(R.drawable.btn_disable_selector);
//                bt_login.setClickable(false);

            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    /**
     * 密码输入监听
     */
    private TextWatcher passwordEdit = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
//            Log.i("123", "phoneNumberEdit-start:" + start + before);
            if (et_number.length() > 0) {
                isComplete = true;
            } else {
                isComplete = false;
            }
            if ((et_password.length() >= 6) && isComplete) {
                bt_login.setBackgroundResource(R.drawable.btn_common_selector);
//                bt_login.setClickable(true);
            } else {
                bt_login.setBackgroundResource(R.drawable.btn_disable_selector);
//                bt_login.setClickable(false);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };
}

